<?php
class ModelMarketingGround extends Model {
  public function addGround($data) {
    $this->event->trigger('pre.admin.ground.add', $data);

    $this->db->query("INSERT INTO " . DB_PREFIX . "ground SET fullname = '" . $this->db->escape($data['fullname']) . "', email = '" . $this->db->escape($data['email']) . "', telephone = '" . $this->db->escape($data['telephone']) . "', code = '" . $this->db->escape($data['code']) . "',  status = '" . (int)$data['status'] . "', date_added = NOW()");

    $ground_id = $this->db->getLastId();

    $this->event->trigger('post.admin.ground.add', $ground_id);

    return $ground_id;
  }

  public function editGround($ground_id, $data) {
    $this->event->trigger('pre.admin.ground.edit', $data);

    $this->db->query("UPDATE " . DB_PREFIX . "ground SET fullname = '" . $this->db->escape($data['fullname']) . "', email = '" . $this->db->escape($data['email']) . "', telephone = '" . $this->db->escape($data['telephone']) . "', code = '" . $this->db->escape($data['code']) . "',  status = '" . (int)$data['status'] . "' WHERE ground_id = '" . (int)$ground_id . "'");

    // if ($data['password']) {
    //   $this->db->query("UPDATE " . DB_PREFIX . "ground SET salt = '" . $this->db->escape($salt = token(9)) . "', password = '" . $this->db->escape(sha1($salt . sha1($salt . sha1($data['password'])))) . "' WHERE ground_id = '" . (int)$ground_id . "'");
    // }

    $this->event->trigger('post.admin.ground.edit', $ground_id);
  }

  public function deleteGround($ground_id) {
    $this->event->trigger('pre.admin.ground.delete', $ground_id);

    $this->db->query("DELETE FROM " . DB_PREFIX . "ground WHERE ground_id = '" . (int)$ground_id . "'");

    $this->event->trigger('post.admin.ground.delete', $ground_id);
  }

  public function getGround($ground_id) {
    $query = $this->db->query("SELECT DISTINCT * FROM " . DB_PREFIX . "ground WHERE ground_id = '" . (int)$ground_id . "'");

    return $query->row;
  }

  public function getGroundByEmail($email) {
    $query = $this->db->query("SELECT DISTINCT * FROM " . DB_PREFIX . "ground WHERE LCASE(email) = '" . $this->db->escape(utf8_strtolower($email)) . "'");

    return $query->row;
  }

  public function getGrounds($data = array()) {
    // $sql = "SELECT *, a.fullname AS name, (SELECT SUM(at.amount) FROM " . DB_PREFIX . "ground_transaction at WHERE at.ground_id = a.ground_id GROUP BY at.ground_id) AS balance FROM " . DB_PREFIX . "ground a";
    $sql = "SELECT *, a.fullname AS name FROM " . DB_PREFIX . "ground a";

    $implode = array();

    if (!empty($data['filter_name'])) {
      $implode[] = "a.fullname LIKE '%" . $this->db->escape($data['filter_name']) . "%'";
    }

    if (!empty($data['filter_email'])) {
      // $implode[] = "LCASE(a.email) = '" . $this->db->escape(utf8_strtolower($data['filter_email'])) . "'";
      $implode[] = "LCASE(a.email) like '%" . $this->db->escape(utf8_strtolower($data['filter_email'])) . "%'";
    }

    if (!empty($data['filter_code'])) {
      $implode[] = "a.code = '" . $this->db->escape($data['filter_code']) . "'";
    }

    if (isset($data['filter_status']) && !is_null($data['filter_status'])) {
      $implode[] = "a.status = '" . (int)$data['filter_status'] . "'";
    }

    if (isset($data['filter_approved']) && !is_null($data['filter_approved'])) {
      $implode[] = "a.approved = '" . (int)$data['filter_approved'] . "'";
    }

    if (!empty($data['filter_date_added'])) {
      $implode[] = "DATE(a.date_added) = DATE('" . $this->db->escape($data['filter_date_added']) . "')";
    }

    if ($implode) {
      $sql .= " WHERE " . implode(" AND ", $implode);
    }

    $sort_data = array(
      'name',
      'a.email',
      'a.code',
      'a.status',
      'a.approved',
      'a.date_added'
    );

    if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
      $sql .= " ORDER BY " . $data['sort'];
    } else {
      $sql .= " ORDER BY name";
    }

    if (isset($data['order']) && ($data['order'] == 'DESC')) {
      $sql .= " DESC";
    } else {
      $sql .= " ASC";
    }

    if (isset($data['start']) || isset($data['limit'])) {
      if ($data['start'] < 0) {
        $data['start'] = 0;
      }

      if ($data['limit'] < 1) {
        $data['limit'] = 20;
      }

      $sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
    }

    $query = $this->db->query($sql);

    return $query->rows;
  }

  public function approve($ground_id) {
    $ground_info = $this->getGround($ground_id);

    if ($ground_info) {
      $this->event->trigger('pre.admin.ground.approve', $ground_id);

      $this->db->query("UPDATE " . DB_PREFIX . "ground SET approved = '1' WHERE ground_id = '" . (int)$ground_id . "'");

      $this->load->language('mail/ground');

      $message  = sprintf($this->language->get('text_approve_welcome'), html_entity_decode($this->config->get('config_name'), ENT_QUOTES, 'UTF-8')) . "\n\n";
      $message .= $this->language->get('text_approve_login') . "\n";
      $message .= HTTP_CATALOG . 'index.php?route=ground/login' . "\n\n";
      $message .= $this->language->get('text_approve_services') . "\n\n";
      $message .= $this->language->get('text_approve_thanks') . "\n";
      $message .= html_entity_decode($this->config->get('config_name'), ENT_QUOTES, 'UTF-8');

      $mail = new Mail();
      $mail->protocol = $this->config->get('config_mail_protocol');
      $mail->parameter = $this->config->get('config_mail_parameter');
      $mail->smtp_hostname = $this->config->get('config_mail_smtp_hostname');
      $mail->smtp_username = $this->config->get('config_mail_smtp_username');
      $mail->smtp_password = html_entity_decode($this->config->get('config_mail_smtp_password'), ENT_QUOTES, 'UTF-8');
      $mail->smtp_port = $this->config->get('config_mail_smtp_port');
      $mail->smtp_timeout = $this->config->get('config_mail_smtp_timeout');

      $mail->setTo($ground_info['email']);
      $mail->setFrom($this->config->get('config_email'));
      $mail->setSender(html_entity_decode($this->config->get('config_name'), ENT_QUOTES, 'UTF-8'));
      $mail->setSubject(sprintf($this->language->get('text_approve_subject'), html_entity_decode($this->config->get('config_name'), ENT_QUOTES, 'UTF-8')));
      $mail->setText($message);
      $mail->send();

      $this->event->trigger('post.admin.ground.approve', $ground_id);
    }
  }

  public function getGroundsByNewsletter() {
    $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "ground WHERE newsletter = '1' ORDER BY fullname, email");

    return $query->rows;
  }

  public function getTotalGrounds($data = array()) {
    $sql = "SELECT COUNT(*) AS total FROM " . DB_PREFIX . "ground";

    $implode = array();

    if (!empty($data['filter_name'])) {
      $implode[] = "fullname LIKE '%" . $this->db->escape($data['filter_name']) . "%'";
    }

    if (!empty($data['filter_email'])) {
      $implode[] = "LCASE(email) = '" . $this->db->escape(utf8_strtolower($data['filter_email'])) . "'";
    }

    if (isset($data['filter_status']) && !is_null($data['filter_status'])) {
      $implode[] = "status = '" . (int)$data['filter_status'] . "'";
    }

    if (isset($data['filter_approved']) && !is_null($data['filter_approved'])) {
      $implode[] = "approved = '" . (int)$data['filter_approved'] . "'";
    }

    if (!empty($data['filter_date_added'])) {
      $implode[] = "DATE(date_added) = DATE('" . $this->db->escape($data['filter_date_added']) . "')";
    }

    if ($implode) {
      $sql .= " WHERE " . implode(" AND ", $implode);
    }

    $query = $this->db->query($sql);

    return $query->row['total'];
  }

  public function getTotalGroundsAwaitingApproval() {
    $query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "ground WHERE status = '0' OR approved = '0'");

    return $query->row['total'];
  }

  public function getTotalGroundsByCountryId($country_id) {
    $query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "ground WHERE country_id = '" . (int)$country_id . "'");

    return $query->row['total'];
  }

  public function getTotalGroundsByZoneId($zone_id) {
    $query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "ground WHERE zone_id = '" . (int)$zone_id . "'");

    return $query->row['total'];
  }

  public function addTransaction($ground_id, $description = '', $amount = '', $order_id = 0) {
    $ground_info = $this->getGround($ground_id);

    if ($ground_info) {
      $this->event->trigger('pre.admin.ground.transaction.add', $ground_id);

      $this->db->query("INSERT INTO " . DB_PREFIX . "ground_transaction SET ground_id = '" . (int)$ground_id . "', order_id = '" . (float)$order_id . "', description = '" . $this->db->escape($description) . "', amount = '" . (float)$amount . "', date_added = NOW()");

      $ground_transaction_id = $this->db->getLastId();

      $this->load->language('mail/ground');

      $message  = sprintf($this->language->get('text_transaction_received'), $this->currency->format($amount, $this->config->get('config_currency'))) . "\n\n";
      $message .= sprintf($this->language->get('text_transaction_total'), $this->currency->format($this->getTransactionTotal($ground_id), $this->config->get('config_currency')));

      $mail = new Mail();
      $mail->protocol = $this->config->get('config_mail_protocol');
      $mail->parameter = $this->config->get('config_mail_parameter');
      $mail->smtp_hostname = $this->config->get('config_mail_smtp_hostname');
      $mail->smtp_username = $this->config->get('config_mail_smtp_username');
      $mail->smtp_password = html_entity_decode($this->config->get('config_mail_smtp_password'), ENT_QUOTES, 'UTF-8');
      $mail->smtp_port = $this->config->get('config_mail_smtp_port');
      $mail->smtp_timeout = $this->config->get('config_mail_smtp_timeout');

      $mail->setTo($ground_info['email']);
      $mail->setFrom($this->config->get('config_email'));
      $mail->setSender(html_entity_decode($this->config->get('config_name'), ENT_QUOTES, 'UTF-8'));
      $mail->setSubject(sprintf($this->language->get('text_transaction_subject'), html_entity_decode($this->config->get('config_name'), ENT_QUOTES, 'UTF-8')));
      $mail->setText($message);
      $mail->send();

      $this->event->trigger('post.admin.ground.transaction.add', $ground_transaction_id);

      return $ground_transaction_id;
    }
  }

  public function deleteTransaction($order_id) {
    $this->event->trigger('pre.admin.ground.transaction.delete', $order_id);

    $this->db->query("DELETE FROM " . DB_PREFIX . "ground_transaction WHERE order_id = '" . (int)$order_id . "'");

    $this->event->trigger('post.admin.ground.transaction.delete', $order_id);
  }

  public function getTransactions($ground_id, $start = 0, $limit = 10) {
    if ($start < 0) {
      $start = 0;
    }

    if ($limit < 1) {
      $limit = 10;
    }

    $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "ground_transaction WHERE ground_id = '" . (int)$ground_id . "' ORDER BY date_added DESC LIMIT " . (int)$start . "," . (int)$limit);

    return $query->rows;
  }

  public function getTotalTransactions($ground_id) {
    $query = $this->db->query("SELECT COUNT(*) AS total  FROM " . DB_PREFIX . "ground_transaction WHERE ground_id = '" . (int)$ground_id . "'");

    return $query->row['total'];
  }

  public function getTransactionTotal($ground_id) {
    $query = $this->db->query("SELECT SUM(amount) AS total FROM " . DB_PREFIX . "ground_transaction WHERE ground_id = '" . (int)$ground_id . "'");

    return $query->row['total'];
  }

  public function getTotalTransactionsByOrderId($order_id) {
    $query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "ground_transaction WHERE order_id = '" . (int)$order_id . "'");

    return $query->row['total'];
  }

  public function getTotalLoginAttempts($email) {
    $query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "ground_login` WHERE `email` = '" . $this->db->escape($email) . "'");

    return $query->row;
  }

  public function deleteLoginAttempts($email) {
    $this->db->query("DELETE FROM `" . DB_PREFIX . "ground_login` WHERE `email` = '" . $this->db->escape($email) . "'");
  }
}